package services

import (
	"errors"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
	"time"
)

//弃用 CheckCode 代替
//func (this *Service) GetSmscodeByMobileAndCode(mobile, code string) (*models.Smscode, error) {
//    fName := "GetSmscodeByMobileAndCode"
//    smscode, err := repository.GetSmscodeParam(map[string]interface{}{
//        "mobile":mobile,
//        "code":code,
//        "status":0,
//        "create_time":map[string]interface{}{">":timehelper.Now().Add(timehelper.Duration(-30) * timehelper.Minute)},
//    }, "create_time desc")
//    if err != nil {
//        return nil, fmt.Errorf("%s%s", this.getFuncName(fName), err.Error())
//    }
//    if smscode.Id <= 0 {
//        return nil, fmt.Errorf("%s smscode not exist", this.getFuncName(fName))
//    }
//    return smscode, nil
//}

func (s *Service) UpdateSmscode(smscode *models_main.Smscode) error {
	return db_main.UpdateSmscode(smscode)
}

func (s *Service) GetSmscodeByMobileLastMin(mobile string) (int64, error) {
	return db_main.GetSmscodeCount(map[string]interface{}{
		"mobile":      mobile,
		"status":      0,
		"create_time": map[string]interface{}{">": time.Now().Add(time.Duration(-1) * time.Minute)},
	})
}

func (s *Service) GetSmscodeByRequestIpLastMin(requestIp string) (int64, error) {
	return db_main.GetSmscodeCount(map[string]interface{}{
		"request_ip":  requestIp,
		"status":      0,
		"create_time": map[string]interface{}{">": time.Now().Add(time.Duration(-1) * time.Minute)},
	})
}

func (s *Service) CheckCode(mobile, code string) error {
	if code == _const.POWER_CODE && cache.GetConfigPub().PowerMode == 1 {
		return nil
	}
	smscode, err := db_main.GetSmscodeParam(map[string]interface{}{
		"mobile": mobile,
		"code":   code,
		"status": 0,
	}, "create_time desc")
	if err != nil {
		global.Log.Infof("check code error :", err)
		return errors.New("验证码错误.")
	}
	if smscode.Id <= 0 {
		global.Log.Infof("sms can not match:%s,%s", mobile, code)
		return errors.New("验证码错误")
	}
	// "create_time": map[string]interface{}{">=": timehelper.Now().Add(timehelper.Duration(-5) * timehelper.Minute)},
	if smscode.CreateTime.Before(time.Now().Add(time.Duration(-5) * time.Minute)) {
		return errors.New("验证码超时")
	}
	smscode.Status = 1
	err = db_main.UpdateSmscode(smscode)
	if err != nil {
		global.Log.Error("update code error : ", smscode)
		return errors.New("系统超时请重试")
	}
	return nil
}
